package com.xhu.base;


import org.apache.logging.log4j.util.PropertiesUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * MySQL数据库连接类
 * @author 王涛
 * @Created by WT on 2019/3/25.
 */
public class ConnectionMySQL {
    /**
     * 数据库管理员用户名
     */
    private static final String USERNAME = getValue("dbconfig.properties", "jdbc.username");
    /**
     * 管理员密码
     */
    private static final String PASSWORD = getValue("dbconfig.properties", "jdbc.password");
    /**
     * 数据库连接的URL
     */
    private static final String DB_URL = getValue("dbconfig.properties", "jdbc.url");


    /**
     * 数据库连接函数
     * @return  返回一个数据库的连接
     */
    public static Connection openConnection(){
        try {
            Class.forName(getValue("dbconfig.properties", "jdbc.driver"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            return DriverManager.getConnection(DB_URL,USERNAME,PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println("数据库连接失败");
        return null;
    }

    /**
     * 通过传入的路径及key，获得对应的值
     * @param path  路径
     * @param key   关键词
     * @return  对应的值
     */
    public static String getValue(String path, String key)
    {
        Properties properties = new Properties();
        try
        {
            properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(path));
        }
        catch (IOException e)
        {
            throw new RuntimeException("配置文件加载失败！", e);
        }
        return properties.getProperty(key);
    }

}
